//
//  MTCConcretePriceViewController.m
//  ERP
//
//  Created by goldeney on 15/4/20.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MTCConcretePriceViewController.h"

#import "GEPickerTextField.h"
#import "NSDictionary+DataFormat.h"

#import "MJRefresh.h"
#import "UITableView+Custom.h"

#import "GEInputTableViewCell.h"
#import "MTCConcretePriceViewCell.h"
#import "MTCConcreteModifPriceViewController.h"

@interface MTCConcretePriceViewController()

@property (nonatomic,strong) NSString *concreteID;
@property (strong, nonatomic) NSMutableArray *resultData;

@property (nonatomic,assign) BOOL isShowOperationButton;
@property (strong, nonatomic) NSArray *timeResultData;

@end

@implementation MTCConcretePriceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"砼价格"];
        
        NSArray *mainMenuArray1 = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_TJGGL_CZ"];
        if (mainMenuArray1.count>0){
            self.isShowOperationButton = YES;
            UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStyleDone target:self
                                                                          action:@selector(addConcretePriceSelector:)];
            self.navigationItem.rightBarButtonItem = leftButton;
        }
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    [self setupRefresh];
}

- (void)getPassingParameter:(id)object
{
    if ([object isKindOfClass:[NSString class]])
        self.concreteID = object;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self getJobOrderInfo];
}

#pragma mark 网络获取数据

- (void)getJobOrderInfo
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_TDJ_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"合同ID" value:self.concreteID];
    [content addParameterKey:@"生效时间" value:@""];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView headerEndRefreshing];
        [self.resultData removeAllObjects];
        
        //保存历史生效时间
        if (result.resultArray && result.resultArray.count >=2)
        self.timeResultData = [result.resultArray firstObject];
        
        //添加数据，刷新页面
        NSArray *firstArray = [self analysisAndFindArray:result.resultArray];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else{
            [self.tableView setTableViewNotDataDrawText:@"暂无新增砼价格" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (NSMutableArray*)analysisAndFindArray:(NSArray*)array
{
    //数据查询
    NSMutableArray *compArray = [NSMutableArray arrayWithArray:[array firstObject]];
    NSMutableArray *htArray = [NSMutableArray arrayWithArray:[array lastObject]];
    
    NSMutableArray *resultArray = [NSMutableArray array];
    for(int i=0;i<compArray.count;i++){
        NSDictionary *dic = [compArray objectAtIndex:i];
        NSString *keyTime = [dic objectFormatStringForKey:@"Time"];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Time == %@", keyTime];
        NSArray *filteredArray = [htArray filteredArrayUsingPredicate:predicate];
        [resultArray addObject:filteredArray];
    }
    
    return resultArray;
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.resultData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [self.resultData objectAtIndex:section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"MTCConcretePriceViewController"];
    MTCConcretePriceViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil){
        cell = [[MTCConcretePriceViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSArray *array = [self.resultData objectAtIndex:indexPath.section];
    NSDictionary *valueDic = [array objectAtIndex:indexPath.row];
    cell.QDDJLabel.text = [NSString stringWithFormat:@"%@",[valueDic objectFormatStringForKey:@"强度等级"]];
    cell.JGLabel.text = [NSString stringWithFormat:@"%@元/方",[valueDic objectFormatStringForKey:@"价格"]];
    
    BOOL isHS = [[valueDic objectFormatIntegerNumberForKey:@"是否含税"] boolValue];
    cell.SFHSLabel.text = [NSString stringWithFormat:@"(%@)", isHS ? @"含税" : @"不含税"];
    
    NSString *BZ = [valueDic objectFormatStringForKey:@"备注"];
    BZ = BZ && BZ.length>0 ? BZ : @"无";
    cell.BZLabel.text = BZ;
    
    //添加分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 0.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [cell.contentView addSubview:lineView];
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 35)];
    view.backgroundColor = [UIColor colorWithWhite:0.985 alpha:1];
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 25, 25)];
    image.image = [UIImage imageNamed:@"oa"];
    //image.contentMode = UIViewContentModeCenter;
    [view addSubview:image];
    
    NSArray *array = [self.resultData objectAtIndex:section];
    NSDictionary *mDictionary = [array firstObject];
    NSString *title = [mDictionary objectFormatStringForKey:@"Time"];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(35, 0, SuperWidth - 40, 35)];
    lable.textColor = [UIColor grayColor];
    //lable.textAlignment = NSTextAlignmentCenter;
    lable.font = [UIFont systemFontOfSize:17];
    lable.text = title;
    [view addSubview:lable];
    
    if (self.isShowOperationButton) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(SuperWidth - 50, 0, 50, 35)];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTitle:@"修改" forState:UIControlStateNormal];
        button.tag = section;
        [button addTarget:self action:@selector(setEditingSelector:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 34, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}


#pragma mark Button Event

- (void)addConcretePriceSelector:(id)sender
{
    MTCConcreteModifPriceViewController *view = [[MTCConcreteModifPriceViewController alloc] initWithConcreteID:self.concreteID takeTime:nil historyTime:self.timeResultData];
    [view setValue:@[self.concreteID, self.timeResultData]];
    view.backResultDelagate = self;
    [self.navigationController pushViewController:view animated:YES];
}

- (void)setEditingSelector:(id)sender
{
    UIButton *button = sender;
    NSInteger section = button.tag;
    
    NSArray *array = [self.resultData objectAtIndex:section];
    NSDictionary *mDictionary = [array firstObject];
    NSString *time = [mDictionary objectFormatStringForKey:@"Time"];
    
    MTCConcreteModifPriceViewController *view = [[MTCConcreteModifPriceViewController alloc] initWithConcreteID:self.concreteID takeTime:time historyTime:self.timeResultData];
    view.backResultDelagate = self;
    [self.navigationController pushViewController:view animated:YES];
}

#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    if (key && [key isEqualToString:@"ModifSuccess"]) {
        [self.resultData removeAllObjects];
        [self.tableView reloadData];
        [self.tableView headerBeginRefreshing];
    }
}

@end
